﻿package
{
	import com.AStar;
	import com.GraphicTile;
	import com.greensock.TweenLite;
	import com.Grid;
	import com.IsoUtils;
	import com.IsoWorld;
	import com.Node;
	import com.Point3D;
	import com.Avatar;
	import com.FriendsBar;
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;	
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	import flash.events.MouseEvent;
	import flash.geom.Point;


	[SWF(backgroundColor=0x000000)]
	public class demo extends MovieClip
	{	
		// api
		private const SESSION_ID:String = "2.NLQYtETtDVMVeOYVjLW_ew__.86400.1263873600-100000300332385";
		
		private var loading_mc:Loader;
		private var containerPic:Sprite;
		
		private var scrollBar:FriendsBar;
		private var scrollX:Number;
		
		// game
		private const GRID_COLS:int = 20;
		private const GRID_ROWS:int = 20;
		
		private var cursor:GraphicTile;
		private var world:IsoWorld;
		private var player:Avatar;
		private var _grid:Grid;
		private var _index:int;
		private var _path:Array;
		private var timer:Timer;
		private var targetX:Number;
		private var targetZ:Number;
		private var modeX:Boolean;
		private var modeZ:Boolean;
		private var walkSpeed:Number = 2;
		
		public function demo()
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			// load api data
			this.loaderInfo.addEventListener(Event.COMPLETE, getSessionKey);
			
			// using timer to move player
			timer = new Timer(100);
			timer.addEventListener(TimerEvent.TIMER, walk);
			
			// create grid and define unwalkable area
			makeWorld();
			
			// create player
			makePlayer();
			
			// cursor
			//cursor = new GraphicTile(20, _cursor, 20, 10);
			//world.addChildToFloor(cursor);
		}
		
		private function getSessionKey(e:Event):void 
		{
			var flashVars:Object = this.root.loaderInfo.parameters;
			var str:String = flashVars.fb_sig_session_key;
			
			if(str != null)
			{
				session_txt.text = "get from flashvars";
			}
			else
			{
				str = SESSION_ID;
				session_txt.text = "fixed session";
			}
			
			debug_txt.text = str;
			
			var fb:FacebookService = new FacebookService(str);
			fb.addEventListener("getFriends", showFriend);
			fb.getFriends();
		}
		
		private function onIOError(e:IOErrorEvent):void 
		{
			trace("IOError");
		}
		
		private function onLoadedPic(e:Event):void
		{
			trace("complete");
		}
		
		private function showFriend(e:FacebookServiceEvent):void
		{
			var xml:XML = e.result;		
			
			var listPhotos:Array = [];
			
			for (var i:int = 0; i <  xml.item.length(); i++)
			{
				listPhotos.push(xml.item[i].pic_square);
			}
			
			scrollBar = new FriendsBar();
			scrollBar.x = 0;
			scrollBar.y = 520;
			scrollBar.addEventListener(Event.COMPLETE, onCompleteBar);
			scrollBar.loadPic(listPhotos);
			addChild(scrollBar);
			
		}
		
		private function onCompleteBar(e:Event):void
		{
			stage.addEventListener(Event.ENTER_FRAME, onScrollPic);
			trace("bar complete");
		}
		
		private function onScrollPic(e:Event):void
		{	
			if (mouseY > scrollBar.y && mouseY < scrollBar.y + 50)
			{
				var ratio:Number = (mouseX - stage.stageWidth/2)/stage.stageWidth/2;
				scrollX = ratio * 80;					
				scrollBar.x += scrollX;
			}
			else
			{
				scrollX *= 0.9;
				scrollBar.x += scrollX;
			}
			
			if (scrollBar.x < -scrollBar.range)
			{
				scrollBar.x = -scrollBar.range;
			}
			else if (scrollBar.x > 10)
			{
				scrollBar.x = 10;
			}
		}
		
		private function makePlayer():void
		{
			player = new Avatar();
			
			player.position = new Point3D(20*19, 0, 20*19);
			world.addChildToWorld(player);
		}
		
		private function makeWorld():void
		{
			world = new IsoWorld();
			world.x = stage.stageWidth / 2;
			world.y = 100;
			addChild(world);		
			
			_grid = new Grid(GRID_COLS, GRID_ROWS);

			for(var _x:int = 0; _x < GRID_COLS; _x++)
			{
				for(var _z:int = 0; _z < GRID_ROWS; _z++)
				{
					var floor:GraphicTile = new GraphicTile(20, _floor, 20, 10);
					floor.position = new Point3D(_x * 20, 0, _z * 20);
					world.addChildToFloor(floor);
				}
			}
			
			drawFuniture();
			
			world.addEventListener(MouseEvent.CLICK, onMove);
			//addEventListener(Event.ENTER_FRAME, onWorldOver);
		}
		
		private function drawFuniture():void
		{
			
			var table:GraphicTile = new GraphicTile(20, _table, 70, 20);
			table.position = new Point3D(140, 0, 280);
			world.addChildToWorld(table);
			
			_grid.setWalkable(6, 15, false);
			_grid.setWalkable(6, 16, false);
			_grid.setWalkable(7, 15, false);
			_grid.setWalkable(7, 16, false);
			_grid.setWalkable(7, 17, false);
			_grid.setWalkable(8, 15, false);
			_grid.setWalkable(9, 15, false);
			_grid.setWalkable(10, 15, false);
			_grid.setWalkable(11, 15, false);
			_grid.setWalkable(12, 15, false);
			_grid.setWalkable(13, 15, false);
			_grid.setWalkable(7, 14, false);
			_grid.setWalkable(6, 14, false);			
			_grid.setWalkable(8, 14, false);
			_grid.setWalkable(9, 14, false);
			_grid.setWalkable(10, 14, false);
			_grid.setWalkable(11, 14, false);
			_grid.setWalkable(12, 14, false);
			_grid.setWalkable(13, 14, false);
			_grid.setWalkable(12, 16, false);
			_grid.setWalkable(13, 16, false);
			_grid.setWalkable(12, 17, false);
			_grid.setWalkable(13, 17, false);
			
		}

		private function onWorldOver(e:Event):void 
		{
			var pos:Point3D = IsoUtils.screenToIso(new Point(world.mouseX, world.mouseY));
			pos.x = Math.round(pos.x / 20) * 20;
			pos.y = Math.round(pos.y / 20) * 20;
			pos.z = Math.round(pos.z / 20) * 20;
			cursor.position = pos;
		}
		
		private function onMove(e:MouseEvent):void
		{
			var pos:Point3D = IsoUtils.screenToIso(new Point(world.mouseX, world.mouseY));
			pos.x = Math.round(pos.x / 20);
			pos.z = Math.round(pos.z / 20);	
			
			if ((pos.x >= 0 && pos.x < GRID_COLS) && (pos.z >= 0 && pos.z < GRID_ROWS))
			{
				_grid.setStartNode(player.x / 20, player.z / 20);
				_grid.setEndNode(pos.x, pos.z);
				findPath();
			}
		}
		
		private function findPath():void
		{
			var astar:AStar = new AStar();
			if(astar.findPath(_grid))
			{
				_path = astar.path;
				_index = 0;
				timer.start();
			}
		}
		
		private function walk(e:TimerEvent):void
		{
			targetX = _path[_index].x * 20;
			targetZ = _path[_index].y * 20;
			
			
			if (targetX> player.x)
			{
				player.frontRight();
				modeX = true;
			}
			else if (targetX < player.x)
			{
				player.backLeft();
				modeX = false;
			}
			else if (targetZ > player.z)
			{
				player.frontLeft();
				modeZ = true;
			}
			else if (targetZ < player.z)
			{
				player.backRight();
				modeZ = false;
			}
						
			player.x = targetX;
			player.z = targetZ;
			
			_index++;
			
			if (_index == _path.length)
			{
				timer.stop();
			}
			
		}
		
		private function walking(e:Event):void
		{
			world.sort();
			trace("in");
			
			if (modeX)
			{
				player.x += walkSpeed;
				if (player.x >= targetX)
				{
					removeEventListener(Event.ENTER_FRAME, walking);
					endWalk(targetX, targetZ);
				}
				
			}else if(!modeX)
			{
				player.x -= walkSpeed;
				if (player.x <= targetX)
				{
					removeEventListener(Event.ENTER_FRAME, walking);
					endWalk(targetX, targetZ);
				}
			}else if (modeZ)
			{
				player.z += walkSpeed;
				if (player.z >= targetZ)
				{
					removeEventListener(Event.ENTER_FRAME, walking);
					endWalk(targetX, targetZ);
				}
			}
			else if(!modeZ)
			{
				player.z -= walkSpeed;
				if (player.z <= targetZ)
				{
					removeEventListener(Event.ENTER_FRAME, walking);
					endWalk(targetX, targetZ);
				}
			}				
		}
		
		private function endWalk(_x:Number,_z:Number):void
		{
			player.x = _x;
			player.z = _z;
			_index++;
			
			if (_index == _path.length)
			{
				//timer.stop();
				
			}else
			{		
				removeEventListener(Event.ENTER_FRAME, walking);		
				//walk();
			}
		}
	}
}